import random
import json
from loguru import logger
from FindWay.configs import config

"""
反向生成map
"""

class MapRestorer:
    def __init__(self):
        self.road_model = None
        self.start_ip = None
        self.end_ip = None
        self.ids = {}

    def restore_map(self, seed, rows, cols):
        random.seed(seed)
        # 保证一定比例的可通行区域
        min_accessible_cells = int(rows * cols * config.min_accessible_ratio)
        accessible_cells = set()
        if config.min_accessible_ratio == 0:
            raise ValueError("Invalid min_accessible_ratio: 0")
        while len(accessible_cells) < min_accessible_cells:
            row = random.randint(0, rows - 1)
            col = random.randint(0, cols - 1)
            accessible_cells.add((row, col))
        self.road_model = [[0] * cols for _ in range(rows)]
        for row, col in accessible_cells:
            self.road_model[row][col] = 1

        # 如果是单行地图，确保至少有两个可通行位置
        if rows == 1:
            while sum(self.road_model[0]) < 2:
                new_col = random.randint(0, cols - 1)
                if self.road_model[0][new_col] == 0:
                    self.road_model[0][new_col] = 1

        def find_valid_position_not_wall():
            # 确定可能的起点和终点区域
            valid_positions = [(row, col) for row in range(rows) for col in range(cols) if self.road_model[row][col] == 1]
            if not valid_positions:
                return None
            return {'row': random.choice(valid_positions)[0], 'col': random.choice(valid_positions)[1]}

        self.start_ip = find_valid_position_not_wall()
        self.end_ip = find_valid_position_not_wall()
        while self.end_ip == self.start_ip:
            self.end_ip = find_valid_position_not_wall()

        return self.road_model, self.start_ip, self.end_ip


# 读取 JSON 文件并复原地图
def restore_maps_from_file(file_path):
    logger.info(f"read {file_path}")
    datas = []
    with open(file_path, 'r') as f:
        data = json.load(f)
    for key, value in data.items():
        seed = value['seed']
        datas += [seed]
        id_parts = value['id'].split('-')
        rows = int(id_parts[1])
        cols = int(id_parts[2])
        logger.info(f"get data @seed={seed} and rows={rows} and cols={cols}")
        # map_data = MapRestorer().restore_map(seed, rows, cols)
        # print(f"Map for key {key}: {map_data}")
    return datas



if __name__ == '__main__':
    # 示例用法
    file_path = r"seeds\20241001_201155-3-1-1000.json"  # 替换为实际的文件路径
    map_generator = MapRestorer()
    seeds = restore_maps_from_file(file_path)
    logger.info("Start building maps")
    k = 1
    for seed in seeds:
        data = map_generator.restore_map(seed, 1, 1000)
        logger.info(f"{k}/{len(seeds)} {data[0]}")
        k += 1
